//
//  WebViewViewController.m
//  Weike
//
//  Created by leirz on 15/3/19.
//  Copyright (c) 2015年 winupon. All rights reserved.
//

#import "XGWebViewController.h"
#import "AppUtils.h"
#import "NJKWebViewProgressView.h"

@interface XGWebViewController ()<UIGestureRecognizerDelegate>

@property(nonatomic,retain) UIWebView *webView;
@property(nonatomic,retain) NSString *webpageUrl;

@end

@implementation XGWebViewController
{
//    JSScrollableTabBar *tabBar;
    
    NJKWebViewProgressView *progressView;
    NJKWebViewProgress *progressProxy;
    
    UIBarButtonItem *backBarButton;
    UIBarButtonItem *closeBarButton;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self initSubviews];
    self.navigationController.navigationBarHidden = NO;
    
    __weak typeof (self) weakSelf = self;
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.delegate = weakSelf;
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

- (void)initSubviews
{
    if([AppUtils isNotEmpty:_customTitle]){
        self.title = _customTitle;
    }
    float tabBarHeight = 0.0;
    progressProxy = [[NJKWebViewProgress alloc] init];
    progressProxy.webViewProxyDelegate = self;
    progressProxy.progressDelegate = self;
    
    self.webpageUrl = self.url;
    
    self.webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, tabBarHeight, SCREEN_WIDTH, CONTENT_HEIGHT-tabBarHeight)];
    self.webView.delegate = progressProxy;
    self.webView.backgroundColor = [UIColor whiteColor];
    self.webView.scrollView.decelerationRate = UIScrollViewDecelerationRateNormal;
    self.webView.scalesPageToFit = !self.disableScalesPageToFit;
    self.webView.dataDetectorTypes = UIDataDetectorTypeNone;
    if(![self.url hasPrefix:@"file"]){
        if (self.url != nil && !([self.url hasPrefix:@"http"] || [self.url hasPrefix:@"ftp"])) {
            self.url = [NSString stringWithFormat:@"http://%@", self.url];
        }
        DSLog(@"url:%@", self.url);
        [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.url] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:10]];
    }else{
        [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.url] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:10]];
        DSLog(@"localurl:%@", self.url);
    }
    
    [self.view addSubview:self.webView];
    
    progressView = [[NJKWebViewProgressView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 2)];
    [self.webView addSubview:progressView];
    
    [self initRightBarButton];

}

- (void)initRightBarButton
{
    UIButton *backButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 52, 40)];
    [backButton setImage:[UIImage imageNamed:@"navback_icon1"] forState:UIControlStateNormal];
    //    [backButton setImage:[UIImage imageNamed:@"nav_back_sel"] forState:UIControlStateHighlighted];
    [backButton addTarget:self action:@selector(backButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [backButton setImageEdgeInsets:UIEdgeInsetsMake(0, -15, 0, 0)];
    backBarButton = [[UIBarButtonItem alloc] initWithCustomView:backButton];

    if(!_hideRightButton){
        UIButton *rightButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 40, 50)];
        [rightButton setTitle:@"···" forState:UIControlStateNormal];
        [rightButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        rightButton.titleLabel.font = [UIFont boldSystemFontOfSize:30];
        rightButton.contentHorizontalAlignment=NSTextAlignmentRight;
        [rightButton addTarget:self action:@selector(moreButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    }
    
//    self.navigationItem.leftBarButtonItems = @[backBarButton];
    
}

- (void)moreButtonClick:(id)sender
{
    UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"刷新", @"复制链接", @"在Safari打开", nil];
    sheet.tag = 100;
    [sheet showInView:self.view];
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (actionSheet.tag == 100) {
        if (buttonIndex == 0) {
            [self.webView reload];
        } else if (buttonIndex == 1) {
            [UIPasteboard generalPasteboard].string = self.webpageUrl;
            [Toast makeText:@"已复制"];
        } else if (buttonIndex == 2) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:self.webpageUrl]];
        }
    }
}

- (void)webViewProgress:(NJKWebViewProgress *)webViewProgress updateProgress:(float)progress
{
    [progressView setProgress:progress animated:YES];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    if([AppUtils isEmpty:_customTitle]){
        self.navigationItem.title = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];
        [self.navigationController.navigationBar setTitleTextAttributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:18],NSForegroundColorAttributeName:[UIColor colorWithString:COLOR_FFFFFF]}];
    }
}

- (void)backButtonClick:(id)sender
{
    if (self.webView.canGoBack) {
        self.navigationItem.leftBarButtonItems = @[backBarButton, closeBarButton];
        [self.webView goBack];
    } else {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)closeButtonClick:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

@end
